# coding: utf-8
import os, json, datetime
from django.conf import settings
from stock.models import PbcTradeType, PbcTradeDaily
from .pub_tool import is_can_do


'''
def pbc_queryset_to_json(queryset):
    effective_date_list = []
    content_list = []
    type__cid_list = []
    amount_list = []

    for item in queryset:
        effective_date_list.append(item["effective_date"].strftime("%Y-%m-%d"))
        content_list.append(item["content"])
        type__cid_list.append(item["type__cid"])
        amount_list.append(int(item["amount"]))

    result_dict = {
        "effective_date": effective_date_list,
        "content": content_list,
        "type__cid": type__cid_list,
        "amount": amount_list
    }
    return result_dict
'''


def pbc_queryset_to_json(queryset, date_list=None):
    effective_date_list = []
    content_list = []
    amount_cid_list = []

    if date_list is None:
        for i, item in enumerate(queryset):
            effective_date_list.append(item["effective_date"].strftime("%Y-%m-%d"))
            content_list.append(item["content"])
            amount_cid_list.append([i, int(item["amount"]), item["type__cid"]])
    else:
        qs_len = len(queryset)
        qs_index = 0
        qs_item = queryset[0]

        previous_content = ""
        previous_type__cid = qs_item["type__cid"]
        previous_amount = 0

        for dl_index, dl_item in enumerate(date_list):
            effective_date = qs_item["effective_date"].strftime("%Y-%m-%d")
            effective_date_obj = datetime.datetime.strptime(effective_date, "%Y-%m-%d")
            dl_item_obj = datetime.datetime.strptime(dl_item, "%Y-%m-%d")

            if effective_date_obj == dl_item_obj:
                previous_content = content = qs_item["content"]
                previous_type__cid = type__cid = qs_item["type__cid"]
                previous_amount = amount = int(qs_item["amount"])

                effective_date_list.append(effective_date)
                content_list.append(content)
                amount_cid_list.append([dl_index, amount, type__cid])

                if qs_index + 1 < qs_len:
                    qs_index += 1
                    qs_item = queryset[qs_index]

            elif effective_date_obj > dl_item_obj:
                effective_date_list.append(dl_item)
                content_list.append(previous_content)
                amount_cid_list.append([dl_index, previous_amount, previous_type__cid])

            elif effective_date_obj < dl_item_obj and qs_index + 1 >= qs_len:
                # queryset已到了最后一个值，而date_list还未结束，则后续的值都为queryset的最后一个值
                amount_cid_list.append([dl_index, previous_amount, previous_type__cid])

            elif effective_date_obj < dl_item_obj:
                # 日期小于date_list中的值，表示date_list中不存在该日期，则当前对象不存储于列表中，只取值，作为date_list中的预设值
                previous_content = qs_item["content"]
                previous_type__cid = qs_item["type__cid"]
                previous_amount = int(qs_item["amount"])
                # effective_date_list.append(dl_item)
                # content_list.append(previous_content)
                # amount_cid_list.append([dl_index, previous_amount, previous_type__cid])

                while qs_index + 1 < qs_len:
                    qs_index += 1
                    qs_item = queryset[qs_index]

                    effective_date = qs_item["effective_date"].strftime("%Y-%m-%d")
                    effective_date_obj = datetime.datetime.strptime(effective_date, "%Y-%m-%d")

                    if effective_date_obj == dl_item_obj:
                        previous_content = content = qs_item["content"]
                        previous_type__cid = type__cid = qs_item["type__cid"]
                        previous_amount = amount = int(qs_item["amount"])

                        effective_date_list.append(effective_date)
                        content_list.append(content)
                        amount_cid_list.append([dl_index, amount, type__cid])
                        break
                    elif effective_date_obj > dl_item_obj:
                        effective_date_list.append(dl_item)
                        content_list.append(previous_content)
                        amount_cid_list.append([dl_index, previous_amount, previous_type__cid])
                        break
                    elif effective_date_obj < dl_item_obj:
                        previous_content = qs_item["content"]
                        previous_type__cid = qs_item["type__cid"]
                        previous_amount = int(qs_item["amount"])

    result_dict = {
        "effective_date": effective_date_list,
        "content": content_list,
        "amount_cid": amount_cid_list
    }
    return result_dict


def get_pbc_data(date_list=None, stock_code=None):
    if stock_code is None:
        filepath = os.path.join(settings.TEMP_DIR, 'pbctrade.json')
    else:
        filepath = os.path.join(settings.TEMP_DIR, 'pbctrade-'+stock_code+'.json')

    # current_date = datetime.date.today()
    # if not os.path.exists(filepath) or current_date > datetime.date.fromtimestamp(os.stat(filepath).st_mtime):
    if not os.path.exists(filepath) or is_can_do('get_pbc_data', "09:22", count=3, interval_minute=60)\
            or not check_pbc_data_newest(date_list, stock_code):
        # 文件不存在或当天9:30到12:00之间可以获取数据3次，每次间隔30分钟
        reverse_repo_queryset = PbcTradeDaily.objects.filter(
            type__id__in=(1, 2, 3)).values(
            'effective_date', 'amount', 'content', 'type__cid').distinct().order_by('effective_date')
        mlf_queryset = PbcTradeDaily.objects.filter(
            type_id=4).values(
            'effective_date', 'amount', 'content', 'type__cid').distinct().order_by('effective_date')
        tmlf_queryset = PbcTradeDaily.objects.filter(
            type_id=5).values(
            'effective_date', 'amount', 'content', 'type__cid').distinct().order_by('effective_date')

        reverse_repo_dict = pbc_queryset_to_json(reverse_repo_queryset, date_list=date_list)
        mlf_dict = pbc_queryset_to_json(mlf_queryset, date_list=date_list)
        tmlf_dict = pbc_queryset_to_json(tmlf_queryset, date_list=date_list)

        return_result = {
            "reverse_repo": reverse_repo_dict,
            "mlf": mlf_dict,
            "tmlf": tmlf_dict,
        }

        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(json.dumps(return_result, indent=2, ensure_ascii=False))

        return return_result
    else:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.loads(f.read())


def check_pbc_data_newest(date_list=None, stock_code=None):
    """
    检测pbc最新的json数据是否和股票日期对应（比较最新日期）
    如果是最新的json数据则返回true，否则返回false

    """
    if stock_code is None:
        filepath = os.path.join(settings.TEMP_DIR, 'pbctrade.json')
    else:
        filepath = os.path.join(settings.TEMP_DIR, 'pbctrade-'+stock_code+'.json')

    with open(filepath, 'r', encoding='utf-8') as f:
        pbc_json_data = json.loads(f.read())
        reverse_repo_effective_date_last = pbc_json_data['reverse_repo']['effective_date'][-1]

    # print('#*20')
    # print('reverse_repo_effective_date_last: ', reverse_repo_effective_date_last)
    # print('stock_date_last: ', date_list[-1])
    reverse_repo_effective_date_last = datetime.datetime.strptime(reverse_repo_effective_date_last, "%Y-%m-%d").date()
    stock_date_last = datetime.datetime.strptime(date_list[-1], "%Y-%m-%d").date()

    if reverse_repo_effective_date_last >= stock_date_last:
        return True
    else:
        return False


